﻿namespace CloudNinja.Metering.Web.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Web.Http;
    using System.Web.Http.OData;

    using CloudNinja.Metering.Data;
    using CloudNinja.Metering.Data.Models;

    public class MeterDataRepositoryController : ODataController
    {
        private readonly IMeteringDataRepository meteringRepository;

        public MeterDataRepositoryController(IMeteringDataRepository meteringRepository)
        {
            this.meteringRepository = meteringRepository;
        }

        public async Task<IHttpActionResult> Post(MeterData meterdata)
        {
            if (!this.ModelState.IsValid)
            {
                return this.BadRequest(this.ModelState);
            }

            try
            {
                await this.meteringRepository.WriteAsync(meterdata);
            }
            catch (Exception e)
            {
                if (this.meteringRepository.IfExists(meterdata))
                {
                    return this.Conflict();
                }

                throw;
            }

            return this.Created(meterdata);
        }
    }
}